import NavBar from '@/components/NavBar'
import ArticleItem from '@/pages/Home/component/ArticleItem'
import { RootState } from '@/store'
import { getSearchResults } from '@/store/actions/search'
import { InfiniteScroll } from 'antd-mobile-v5'
import { useState } from 'react'
import { useDispatch, useSelector } from 'react-redux'
import { useLocation } from 'react-router-dom'
import styles from './index.module.scss'

let page = 1
const SearchResult = () => {
  // 获取地址传过来的参数
  const location = useLocation()
  const search = new URLSearchParams(location.search)
  const key = search.get('key')!

  const dispatch = useDispatch()
  // 获取搜索结果
  const results = useSelector((state: RootState) => state.search.results)

  //   useEffect(() => {
  //     dispatch(getSearchResults(key, 1))
  //   }, [dispatch, key])

  // 是否有更多数据
  const [hasMore, setHasMore] = useState(true)
  const [loading, setLoading] = useState(false)
  const loadMore = async () => {
    if (loading) return
    setLoading(true)
    try {
      await dispatch(getSearchResults(key, page))
      page = page + 1
    } finally {
      setHasMore(false)
    }
    if (page > 5) {
      setHasMore(false)
    }
  }
  return (
    <div className={styles.root}>
      {/* 顶部导航栏 */}
      <NavBar className="navBar">搜索结果</NavBar>

      <div className="article-list">
        {results.map((item) => (
          <ArticleItem
            key={item.art_id}
            article={item}
            channelId={-1}
          ></ArticleItem>
        ))}
      </div>
      <InfiniteScroll loadMore={loadMore} hasMore={hasMore}></InfiniteScroll>
    </div>
  )
}

export default SearchResult
